package mo.tags.stack;

import java.util.Stack;

public class L1717 {

    public int maximumGain(String s, int x, int y) {
        Stack<Character> stack = new Stack<>();
        char last = 'a', cur = 'b';
        int res = 0;
        if (y > x) {
            last = 'b';
            cur = 'a';
        }
        for (char c : s.toCharArray()) {
            if (stack.isEmpty() || stack.peek() != last || c != cur) {
                stack.push(c);
            } else {
                stack.pop();
                res += Math.max(x, y);
            }
        }
        Stack<Character> stack1 = new Stack<>();
        while (!stack.isEmpty()) {
            if (stack1.isEmpty() || stack1.peek() != last || stack.peek() != cur) {
                stack1.push(stack.peek());
            } else {
                stack1.pop();
                res += Math.min(x, y);
            }
            stack.pop();
        }
        return res;
    }

}
